﻿using UnityEngine;
using System.Collections.Generic;

public delegate void NetworkEvent(ByteBuffer buffer);

public class NetworkManager : MonoBehaviour {

    private static NetworkManager _instance;
    public static NetworkManager Instance
    {
        get
        {
            return _instance;
        }
    }

    SocketClient client;

    int HeartInterval = 5;

    //存储子线程的消息体
    Queue<ByteBuffer> queue = new Queue<ByteBuffer>();

    private void Awake()
    {
        _instance = this;

        client = new SocketClient();

        EventManager.HeartBeat+=OnHeatBeat;
    }
    private void OnDestroy()
    {
        EventManager.HeartBeat-=OnHeatBeat;

    }
    public void AddEnvent(ByteBuffer buffer)
    {
        queue.Enqueue(buffer);
    }

    private void Update()
    {
        if (queue.Count > 0)
        {
            ByteBuffer buffer = queue.Dequeue();

            //把消息交给事件分发
            EventManager.Instance.OnMessage(buffer);
        }

        CheckHeat();
    }

    //ui调用的发送服务器的方法
    public void SendMessage(int protocol,string json)
    {
        client.SendMessage(protocol,json);
    }

    public void SendMessage(int protocol)
    {
        client.SendMessage(protocol);
    }

    //接收到服务器心跳
    void OnHeatBeat()
    {
        lastHeartTime = Time.time;
        count = 0;

        //返回心跳
        SendMessage(Protocol.HeartBeat);
    }

    float lastHeartTime = 0;
    int count = 0;
    void CheckHeat()
    {
        if(client.online && client.isloggin)
        {
            if (Time.time - lastHeartTime > 5)//心跳超时
            {
                count++;
                lastHeartTime = Time.time;
                Debug.Log("心跳超时一次");
                if (count >= 3)//心跳超时3次
                {
                    count = 0;
                    Debug.Log("心跳超时3次，断线处理");
                    //断线处理
                    client.OnClose();
                }
            }
        }
    }

    public void SetOnline(bool ison)
    {
        client.isloggin = ison;
    }
}
